import api from "./url";
import global from "../global";
import storage from "../utils/storage/index";
/**
 * @param {String} url 
 * @param {Object} params 
 * @param {Function} callback 回调函
 */
const get = (url, params) => {
  console.log("api.home + url", api.home + url)
  // storage.getItem('userInfo', (data) => {
  //   this.setState({
  //     token: data.token,
  //     user_id: data.user_id,
  //   })
  // })
  if (params) {
    let paramsArray = [];
    //拼接参数
    Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
    if (url.search(/\?/) === -1) {
      url += '?' + paramsArray.join('&')
    } else {
      url += '&' + paramsArray.join('&')
    }
  }
  const promise = new Promise((resolve, reject) => {
    //fetch请求
    // if (storage.getItem('token')) {
    fetch(api.home + url, {
      // headers: {
      //   'token': storage.getItem('token')
      // }
    })
      .then((response) => response.json())
      .then((json) => {
        console.log(api.home + url)
        resolve(json)
      })
      .catch((error) => reject(error))
      .finally(() => {
      });
    // } else {
    //   reject('没token')
    // }
  })
  return promise;
}
/*
*  post请求
*  url:请求地址
*  data:参数
*  callback:回调函数
* */
function post(url, params) {
  //fetch请求
  let postRequire = new Request(api.home + url, {
    method: 'post',
    headers: {
      'Content-Type': 'application/json',
      // 'token': storage.getItem('token')
    },
    body: JSON.stringify(params)
  })
  return new Promise((resolve, reject) => {
    fetch(postRequire).then(response => {
      let result = response.text()
      result.then(res => {
        resolve(JSON.parse(res));
      })
    }).catch(err => {
      reject(err);
    })
  })
}
module.exports = {
  get,//普通get请求
  post//普通post请求
}